<!--
  * 巡检记录
  
-->
<template>
  <a-layout style="height: 100%">
    <a-layout-sider style="background-color: white ">

      <a-tree
          v-if="treeData.length > 0"
          default-expand-all="true"
          style="margin-top: 20px"
          :tree-data="treeData"
          :default-expanded-keys="['0-0-0', '0-0-1']"
          @select="onSelect"
      >
<!--        @select="onSelect"
        @check="onCheck"-->
<!--
        <span slot="title0010" style="color: #1890ff">sss</span>
-->
      </a-tree>
  </a-layout-sider>
    <a-layout style="">

      <a-layout-content>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="巡检描述" class="smart-query-form-item">
                <a-input style="width: 150px" v-model:value="queryForm.inspDescribe" placeholder="巡检描述" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="queryDatanew">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    搜索
                </a-button>
              <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            <a-button @click="exportData('tableExcel','result')" class="smart-margin-left10">
                <template #icon>
                  <ReloadOutlined />
                </template>
                导出
              </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
<!--                <a-button @click="confirmBatchDelete" type="danger" size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>-->
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
                size="small"
                id="tableExcel"
                :dataSource="tableData"
                :columns="columns"
                rowKey="id"
                bordered
                :loading="tableLoading"
                :pagination="false"
        >
<!--
          :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
-->

          <template #bodyCell="{ text, record, column }" >
            <template v-if="column.dataIndex === 'action'">
              <div class="smart-table-operate" >
                <a-button @click="showFormxlxq(record)" type="link">线路详情</a-button>

              </div>
            </template>


            <template v-if="column.dataIndex === 'status'">
              <div class="smart-table-operate">
                <!--               {{record.status}}-->
                <div v-if="record.status === 0" style="color: #003b94">巡检中</div>
                <div v-if="record.status === 1" color="red">已完成</div>

              </div>
            </template>
          </template>

        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                    showSizeChanger
                    showQuickJumper
                    show-less-items
                    :pageSizeOptions="PAGE_SIZE_OPTIONS"
                    :defaultPageSize="queryForm.pageSize"
                    v-model:current="queryForm.pageNum"
                    v-model:pageSize="queryForm.pageSize"
                    :total="total"
                    @change="queryData"
                    @showSizeChange="queryData"
                    :show-total="(total) => `共${total}条`"
            />
        </div>

        <GInspectionRecordForm  ref="formRef" @reloadList="queryData"/>
         <Xlxq ref="formRefxlxq" ></Xlxq>
    </a-card>

      </a-layout-content>

    </a-layout>
  </a-layout>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { gInspectionRecordApi } from '/@/api/business/xjgl/g-inspection-record-api';
    import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import GInspectionRecordForm from './g-inspection-record-form.vue';
    import {departmentApi} from "/@/api/system/department-api.js";
    import Xlxq from "/@/views/support/xjgl/xjjl/xlxq.vue";
    import * as XLSX from 'xlsx/xlsx.mjs';
    import FileSaver from "file-saver";
   // import {planIndicatorApi} from "/@/api/water/plan/plan-indicator-api.js";
    // ---------------------------- 表格列 ----------------------------
    const treeData = ref([]);
    onMounted(queryGuanQuTree);

    async function queryGuanQuTree() {
      let res = await departmentApi.queryGuanQuTree();
      treeData.value= res.data;
    }

    function onSelect(keys, event) {
      console.log('Trigger Select', keys, event);

      if(keys[0]!=null){
        queryForm.deptId=keys[0];
        queryData();
      }


    }
    const formRefxlxq = ref();
    function showFormxlxq(data) {
      formRefxlxq.value.show(data);
    }
    const columns = ref([
        {
            title: '组织机构',
            dataIndex: 'deptName',
            ellipsis: true,
        },

        {
            title: '巡检点数',
            dataIndex: 'inspCount',
            ellipsis: true,
        },  {
        title: '巡检描述',
        dataIndex: 'inspDescribe',
        ellipsis: true,
      },{
        title: '线路详情',
        dataIndex: 'lineName',
        ellipsis: true,
      }
      ,
      {
        title: '巡检员',
        dataIndex: 'actualame',
        ellipsis: true,
      },
        {
            title: '开始时间',
            dataIndex: 'startTime',
            ellipsis: true,
        },
        {
            title: '结束时间',
            dataIndex: 'endTime',
            ellipsis: true,
        },
        {
            title: '状态(0巡检中 1已完成)',
            dataIndex: 'status',
            ellipsis: true,
        },
        {
            title: '创建人',
            dataIndex: 'createUserName',
            ellipsis: true,
        },
        {
            title: '更新时间',
            dataIndex: 'modifyTime',
            ellipsis: true,
        },
        {
            title: '更新人',
            dataIndex: 'modifyUserName',
            ellipsis: true,
        },
      {
        title: '操作',
        dataIndex: 'action',
        ellipsis: true,
      },

    ]);
    const  selectedRows =ref([])// 已选择的行
    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
       inspDescribe: "", //描述
        pageNum: 1,
        pageSize: PAGE_SIZE,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);

    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    async function queryDatanew() {
      queryForm.pageNum=1;
      queryData();
    }
    // 查询数据
    async function queryData() {
        tableLoading.value = true;
      console.log(queryForm.deptId==0)
      if(queryForm.deptId==0){
        queryForm.deptId="";
      }

        try {
            let queryResult = await gInspectionRecordApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(queryData);


    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await gInspectionRecordApi.delete(data.id);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {

        selectedRowKeyList.value = selectedRowKeys;
    }


    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }
     function exportData(tablename, filename) {
      console.log("exportData")
       console.log("selectedRowKeyList"+JSON.stringify(selectedRowKeyList))

       const   keys=   selectedRowKeyList._rawValue.toString(). split(',');
       console.log("keys"+keys)
       //const   keys='1,3';
       console.log(keys.includes('1'))
       const date=tableData.value;
       console.log("date"+date)
     /*  date.forEach(item=>{
         if( keys.includes(item.id.toString())){
           console.log(item.id.toString())
         }

       })*/

       const selectedRows = date.filter(row =>
           keys.includes(row.id.toString()));

       console.log(selectedRows)

       //  FileSaver
      var wb = XLSX.utils.book_new()
      var xlsxData = XLSX.utils.table_to_sheet(document.querySelector("#" + tablename))
       //    var xlsxData = XLSX.utils.json_to_sheet(selectedRows)

      XLSX.utils.book_append_sheet(wb, xlsxData, filename)
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
       console.log("exportData")
      try {
        FileSaver.saveAs(
            new Blob([wbout], {type: "application/octet-stream"}),
            filename + '.xlsx'
        )
      } catch (e) {
        if (typeof console !== "undefined")
          console.log(e, wbout)
      }

    }
    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await gInspectionRecordApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

</script>
